<template>
<!-- 健康风险规则组件 -->
  <div>
    <el-table
      :data="tableData"
      style="width: 100%" 
      height="505px"
      ref="multipleTable"
      highlight-current-row
      border
      header-cell-class-name="table-header-class">
      <el-table-column
        label="健康信息类别"
        align='center'
        width="180">
        <template slot-scope="scope">
          <el-select v-model="scope.row.healthType" placeholder="请选择" filterable clearable @change="healthTypeChange(scope.row)" :disabled="pageDisabled">
            <el-option
              v-for="item in healthTypeDic"
              :key="item.id"
              :label="item.dictValue"
              :value="item.id + ''">
            </el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column
        label="健康信息.项目"
        align='center'
        width="180">
        <template slot-scope="scope">
          <el-select v-model="scope.row.healthProjectId" placeholder="请选择" :loading="scope.row._projectLoading" filterable remote clearable :remote-method="remoteMethod" @visible-change="visibleChange($event,scope.$index, scope.row)" @change="healthProjectChange(scope.row,scope.$index)" v-loadMore="loadMore" :disabled="pageDisabled || !scope.row.healthType">
            <el-option
              v-for="item in optionList[scope.$index]"
              :key="item.id"
              :label="item.dictValue"
              :value="item.id + ''">
            </el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column
        label="健康信息结果"
        align='center'
        width="180">
        <template slot-scope="scope" v-if="!scope.row._updataFlag">
          <el-tooltip :disabled="!scope.row.healthProjectValueId" v-if="scope.row.type == '2'" effect="dark" :content="handleResult(scope.row.healthProjectValueId)" placement="top">
            <span :class="['result-item',{'disabled-item': pageDisabled}]" @click="measuringResultClick(scope.row,'健康信息.项目值')">{{handleResult(scope.row.healthProjectValueId)}}</span>
          </el-tooltip>
          <el-select v-model="scope.row.healthProjectValueId" placeholder="请选择" :loading="scope.row._projectValueLoading" filterable clearable v-else-if="scope.row.type == '1' || scope.row.type == '3'" :disabled="pageDisabled" @visible-change="projectValueChange($event,scope.$index, scope.row)">
            <el-option
              v-for="item in projectValueDic[scope.$index]"
              :key="item.id"
              :label="item.label"
              :value="item.id + ''">
            </el-option>
          </el-select>
          <span v-else></span>
        </template>
      </el-table-column>
      <el-table-column
        label="健康信息标志"
        align='center'
        width="350">
        <template slot-scope="scope">
          <el-input v-model="scope.row.hitMark" disabled></el-input>
        </template>
      </el-table-column>
      <el-table-column
        label="评分"
        align='center'
        width="180">
        <template slot-scope="scope">
          <el-input-number v-model="scope.row.scoringItems" :precision="0" placeholder="请输入" :disabled="pageDisabled"></el-input-number>
        </template>
      </el-table-column>
      <el-table-column
        label="评点对象.累加标记"
        align='center'
        width="180">
        <template slot-scope="scope">
          <el-select v-model="scope.row.scoringItemsTag" placeholder="请选择" clearable :disabled="pageDisabled">
            <el-option
              v-for="item in yesOrNoDic"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="操作" align='center' width="150" fixed="right" v-if="!pageDisabled">
        <template slot-scope="scope">
          <div style="display:flex;justify-content: center;">
            <span class="handle-btn" @click="handleAdd(scope.$index, scope.row)">新增</span>
            <span class="handle-btn" @click="handleDel(scope.$index, scope.row)">删除</span>
            <span class="handle-btn" @click="handleCopy(scope.$index, scope.row)">复制</span>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 弹窗 -->
    <!-- 新增疾病规则弹窗 -->
    <el-dialog
      v-if="conditionVisible" 
      title="配置条件"
      :visible.sync="conditionVisible"
      :close-on-click-modal="false"
      width="850px"
      center>
      <conditionRelation ref="conditionRelation" :tableTitle="tableTitle" source="health" :logicDic="logicDic" @saveRelation="()=>{conditionVisible = false}"></conditionRelation>
    </el-dialog>
  </div>
</template>

<script>
  import conditionRelation from "./conditionRelation";

  import constant from '@/utils/constant';
  import {
    getHealthRiskRuleApi,
    // 字典
    getNameDictProjectApi,
    getDiseaseNameApi,
    getHealthRiskRuleTypeApi
  } from "@/api/medicalLibrary/examProjectLibrary";
  import { getCodeDictProject } from "@/api/taskCenter/enterWorkPool";
  import { getHqnrInfo } from "@/api/taskCenter/manualEntry";
  export default {
    directives: {
      loadMore: {
        // el 可以获取当前dom节点， binding一个对象(具体可以自行打印观察)，vnode第三个参数为虚拟节点
        bind (el, binding) {
          // 获取element，定义scroll
          const selectDom = el.querySelector('.el-select-dropdown .el-select-dropdown__wrap');
           // 添加滚动事件
	        selectDom.addEventListener('scroll', function () {
	        // scrollHeight所有数据占据面的一个高度,，scrollTop滚动条滚走的区域高度，clientHeight可视区域面积高度
            const height = selectDom.scrollHeight - selectDom.scrollTop - 5 <= selectDom.clientHeight;
            if (height) {
              binding.value();
            }
          });
        }
      }
    },
    components: {
	  	conditionRelation
	  },
    props: {
      logicDic: {
        type: Array,
        default: ()=>{
          return []
        }
      },
      pageDisabled: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        yesOrNoDic: [{value: '0', label: '否'},{value: '1', label: '是'}],  //是否字典表 
        healthTypeDic: [], //健康分类字典
        optionList: [],  //健康信息-项目列表
        projectValueDic: [],  //健康信息-项目值列表
        tableData: [],
        ruleGroupVersionId: '',  //版本id

        // select框分页
        page: {
          pageNum: 1,
          pageSize: 100,
          parameter: ''
        },
        currentData: {},
        moreFlag: true,
        // 弹窗
        conditionVisible: false,
        tableTitle: '',  //表头名称
      }
    },
    created(){
      this.getNameDictProject()
    },
    methods: {
      // 查询逻辑符
      getNameDictProject(){
        getNameDictProjectApi({name: '健康信息分类'}).then(res => {
					if (res.resultCode == constant.SUCCESS) {
						this.healthTypeDic = res.data
					}
				})
      },
      // 获取疾病的健康风险规则
      getRiskRule(diseaseID,version){
        this.$store.dispatch('loading/CHANGE_LOADING',true)
        this.tableData = []
        this.optionList = []
        this.projectValueDic = []  //健康信息-项目值列表
        getHealthRiskRuleApi({diseaseID,version}).then(res => {
					this.$store.dispatch('loading/CHANGE_LOADING',false)
					if (res.resultCode == constant.SUCCESS) {
						this.tableData = res.data || []

            let coverFlag = true
            if(!this.tableData.length) {
              if(!this.pageDisabled) this.handleAdd(-1)
            }
            else {
              this.ruleGroupVersionId = res.data[0].ruleGroupVersionId
              coverFlag = false
              this.tableData.forEach((item,index)=>{
                if(!item.scoringItems && item.scoringItems!==0) item.scoringItems = undefined

                this.optionList.push(item.healthProjectId && item.healthProjectName ? [{id: item.healthProjectId, dictValue: item.healthProjectName}] : [])
                this.projectValueDic[index] = item.type == '2' || (!item.healthProjectValueId || !item.healthProjectValueName) ? [] : [{id: item.healthProjectValueId, label: item.healthProjectValueName}]
              })
            }
            this.$emit('getCoverFlag',coverFlag,this.ruleGroupVersionId)
					}
				}).catch(err => {
					this.$store.dispatch('loading/CHANGE_LOADING',false);
				});
      },
      // 点击测量结果
      measuringResultClick(row,tableTitle){
        if(this.pageDisabled) return
        this.tableTitle = tableTitle
        this.conditionVisible = true
        setTimeout(()=>{
          // 处理配置条件列表数据
          this.$refs.conditionRelation.currentRow = row
          this.$refs.conditionRelation.handleRelation('healthProjectValueId')
        })
      },
      // 分类改变时触发
      healthTypeChange(row){
        row.healthProjectId = ''
        this.restRowData(row)
      },
      // 项目改变时触发
      healthProjectChange(row,_index){
        /* this.page.pageNum = 1
        this.page.parameter = '' */
        this.$set(row,'_updataFlag',true)
        this.restRowData(row)
        if(row.healthProjectId) {
          // 匹配项目的中文值
          row.healthProjectName = this.optionList[_index].filter(fItem=>fItem.id == row.healthProjectId)[0].dictValue
          this.getHealthRiskRuleType(row)
        }
      },
      // 获取项目值类型
      getHealthRiskRuleType(row){
        getHealthRiskRuleTypeApi({id: row.healthProjectId}).then(res => {
					if (res.resultCode == constant.SUCCESS) {
            this.$set(row,'type',res.data.type)
            this.$set(row,'_updataFlag',false)
					}
				})
      },
      // 项目下拉框获得焦点时触发
      visibleChange(event,_index,row){
        console.log(event,'12');
        if(!event) {
          this.page.pageNum = 1
          this.page.parameter = ''
          return
        }
        this.currentData = {
          index: _index,
          row
        }
        this.$set(row,'_projectLoading',true)
        if(row.healthType == '2' || row.healthType == '4'){
          let params = {
            pageNum: this.page.pageNum, 
            pageSize: this.page.pageSize,
	          parameter: this.page.parameter
          }
          getHqnrInfo(params).then(res => {
            if (res.resultCode == constant.SUCCESS) {
              this.moreFlag = true
              let transferData = this.optionList[_index]
		  	      if(this.page.pageNum == 1) transferData = []
              if(!res.data.list || !res.data.list.length) this.moreFlag = false
		  	      res.data.list.forEach(item => {
		  	      	let obj = {
		  	      		id: item.childCode,
		  	      		dictValue: item.childName
		  	      	}
		  	      	transferData.push(obj);
              })
              
              this.tableData.forEach(fItem =>{
                if((fItem.healthType == '2' || fItem.healthType == '4') && fItem.healthProjectId && fItem.healthProjectName){
                  if(!transferData.some(sItem=>sItem.id == fItem.healthProjectId)) transferData.push({id: fItem.healthProjectId,dictValue: fItem.healthProjectName})
                }
              })
              const map = new Map();
              const newArr = transferData.filter(v => !map.has(v.id) && map.set(v.id, 1));
              this.$set(this.optionList,[_index],newArr)
            }
            this.$set(row,'_projectLoading',false)
          })
          return
        }
        let filterArr = this.healthTypeDic.filter(fItem=>fItem.id == row.healthType)
        getNameDictProjectApi({name: filterArr.length ? filterArr[0].dictValue : row.healthTypeName}).then(res => {
          if (res.resultCode == constant.SUCCESS) {
            this.$set(this.optionList,[_index],res.data)
          }
          this.$set(row,'_projectLoading',false)
        })
      },  
      // 将康信息-项目远程搜索
      remoteMethod(query){
        this.page.parameter = query
        this.page.pageNum = 1
        this.visibleChange(true,this.currentData.index,this.currentData.row)
      },
      // 健康信息-项目触底加载
      loadMore(){
        if(!this.moreFlag || (this.currentData.row.healthType != '2' && this.currentData.row.healthType != '4')) return
        this.page.pageNum += 1
        this.visibleChange(true,this.currentData.index,this.currentData.row)
      },

      // 健康信息-项目值下拉框获得焦点时触发
      projectValueChange(event,_index,row){
        this.$set(row,'_projectValueLoading',true)
        if(event && row.healthProjectId){
          let url = row.type == '3' ? getCodeDictProject : getNameDictProjectApi
          let params = row.type == '3' ? 'cureStatus' : {name: row.healthProjectName}
          url(params).then(res => {
            if (res.resultCode == constant.SUCCESS) {
              if(res.data.length) {
                res.data.forEach(item=>{
                  if(row.type == '3') item.label = item.dictValue
                  else item.label = item.dictValue
                })
              }
              this.$set(this.projectValueDic,[_index],res.data)
            }
            this.$set(row,'_projectValueLoading',false)
          })
        }
      },
      // 清空规则配置行
      restRowData(row){
        row.healthProjectValueId = ''
        row.hitMark = ''
        row.scoringItems = undefined
        row.scoringItemsTag = ''
        row.type = '99'
      },
      // 处理测量结果的显示
      handleResult(measuringResult){
        let result = measuringResult
        if(result) {
          result = result.replace(/\^/g, '').replace(/#/g, '').replace(/\$/g, '').replace(/\("/g, '').replace(/\"\)/g, '')
        }
        return result
      },

      /* ----列表操作按钮 */
      // 添加
      handleAdd(index, row) {
        let obj = {
          healthType: '',
          healthProjectId: '',
          healthProjectValueId: '',
          hitMark: '',
          scoringItems: undefined,
          scoringItemsTag: '',
          type: '99'
        }
        this.tableData.push(obj)
        this.optionList.push([])
        this.projectValueDic.push([])
        /* this.tableData.splice(index+1,0,obj)
        this.optionList.splice(index+1,0,[])
        this.projectValueDic.splice(index+1,0,[]) */
      },
      // 删除
      handleDel(index, row) {
        this.tableData.splice(index,1)
        this.optionList.splice(index,1)
        this.projectValueDic.splice(index,1)
        if(!this.tableData.length) this.handleAdd(-1)
      },
      // 复制
      handleCopy(index, row) {
        let obj = JSON.parse(JSON.stringify(row))
        delete obj.id
        delete obj.hitMark
        this.tableData.push(obj)
        this.optionList.push(JSON.parse(JSON.stringify(this.optionList[index])))
        this.projectValueDic.push(this.projectValueDic[index] ? JSON.parse(JSON.stringify(this.projectValueDic[index])) : [])
        /* this.tableData.splice(index+1,0,obj)
        this.optionList.splice(index+1,0,JSON.parse(JSON.stringify(this.optionList[index])))
        this.projectValueDic.splice(index+1,0,this.projectValueDic[index] ? JSON.parse(JSON.stringify(this.projectValueDic[index])) : []) */
      },

      // 处理保存的数据
      saveHandle(){
        let riskRuleFieds = ['healthType','healthProjectId','healthProjectValueId','hitMark','scoringItems','scoringItemsTag'],
        flag = true,
        msg = ''
        let filterArr = JSON.parse(JSON.stringify(this.tableData))
        filterArr.forEach(fItem=>{
          let itemFlag = false
          if(this.ruleGroupVersionId) fItem.ruleGroupVersionId = this.ruleGroupVersionId
          if(!fItem.scoringItems && fItem.scoringItems !== 0) fItem.scoringItems = ''
          
          riskRuleFieds.forEach(item=>{
            if(fItem[item] || fItem[item] === 0) itemFlag = true
          })
          if(!itemFlag) flag = false
        })
        if(filterArr.some(item=> !item.healthProjectId || !item.healthProjectValueId) && flag){
          flag = false
          msg = '健康信息-项目、健康信息结果必填'
        }
        return {
          flag,
          filterArr,
          msg
        }
      }
    }
  }
</script>
<style lang="less" scoped>
.handle-btn{
  cursor: pointer;
  color: #409eff;
  display: inline-block;
  padding: 0 8px;
}
.result-item{
  color: #40a9fd;
  cursor: pointer;
  width: 100%;
  display: inline-block;
  height: 24px;
  line-height: 30px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.disabled-item{
  color: #606266;
  cursor: no-drop;
}

/deep/ .el-input-number__decrease,/deep/ .el-input-number__increase{
  display: none;
}
</style>